package net.yla.smartbus.core.asp;

import lombok.Cleanup;
import net.yla.smartbus.core.api.RequestCode;
import net.yla.smartbus.core.exception.AppException;
import net.yla.smartbus.core.util.RedisUtil;
import net.yla.smartbus.core.util.SignatureAuthenticationUtil;
import net.yla.smartbus.module.ba.right.login.dto.UserSession;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.Charset;

/**
 * 登录用户拦截器
 *
 * @author ZengXiaoLiang
 **/
@Component

public class LoginUserInterceptor extends HandlerInterceptorAdapter {

    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private SignatureAuthenticationUtil signatureAuthenticationUtil;

    private static final Logger logger = LoggerFactory.getLogger(LoginUserInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        String requestURI = request.getRequestURI();
        System.out.println(requestURI);
        String remoteAddr = request.getRemoteAddr();
        System.out.println(remoteAddr);

//        String ak = request.getHeader("__ak");
//        System.out.println(ak);
//        String body =null;
//        String sign=null;
//        //signatureAuthenticationUtil.SignatureAuthentication(ak,body,sign);
//        // TODO 请求拦截处理
//        String tokenHeader = request.getHeader("__token");
//        String tokenParam = request.getParameter("__token");

//        String bodys = this.getParm(request);logger.info(tokenHeader, tokenParam);
//        JSONObject json = JSONObject.parseObject(bodys);
//        String tokenBody = null;
//        if (json != null) {
//           tokenBody = json.getString("token");
//        }
//        String token = StringUtils.isNotEmpty(tokenHeader) ? tokenHeader : tokenParam;
        /*if (StringUtils.isEmpty(token)) {
            throw new AppException("用户未登录,请先登录!", RequestCode.Not_Login);
        }
        if (redisUtil.get(token) == null) {
            throw new AppException("用户未登录,请先登录!", RequestCode.Not_Login);
        }*/

 /*
        UserSession userSession = (UserSession) redisUtil.get(token);
        // 校验请求是否在权限功能内
        // 请求方式
        String requestMethod = request.getMethod();
        // 请求路径，域名后的部分
        String servletPath = request.getServletPath();*/

        // 校验请求是否在权限内
//		List<FunctionDO> functions = userSession.getFunctions();
//		boolean dto = false;
//		if (ListUtil.isNotEmpty(functions)) {
//			for (FunctionDO f : functions) {
        //	if (servletPath.equals(f.getRequestUrl()) && requestMethod.equalsIgnoreCase(f.getRequestMethod().getName())) {
//					dto = true;
//					break;
//				}
//			}
//		}

        // dto=true，表示请求在权限内
//		if (!dto) {
//			throw new AppException("用户无权限", RequestCode.forbid_error);
//		}

        return super.preHandle(request, response, handler);
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) throws Exception {
        super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
        super.afterCompletion(request, response, handler, ex);
    }

    @Override
    public void afterConcurrentHandlingStarted(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        super.afterConcurrentHandlingStarted(request, response, handler);
    }

    /**
     * 获取POST请求中Body参数
     *
     * @param request
     * @return 字符串
     */
    public String getParm(HttpServletRequest request) throws IOException {
        @Cleanup BufferedReader br = null;
        try {
            br = new BufferedReader(new InputStreamReader(request.getInputStream(), Charset.defaultCharset()));
        } catch (IOException e) {
            e.printStackTrace();
        }
        String line = null;
        StringBuilder sb = new StringBuilder();
        try {
            while ((line = br.readLine()) != null) {
                sb.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (br != null) {
                br.close();
            }
        }
        return sb.toString();
    }
}
